package com.hdu.redisQueryUtils;

import com.alibaba.fastjson.JSON;
import redis.clients.jedis.Jedis;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

public class RedisQueryUitls {

    private final static Jedis JEDIS = new Jedis("localhost", 6379);

    private  final static String EMPTY_VALUE_STR = "null";


    /**
     * 缓存穿透封装
     * @param key
     * @param supplier
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T query(String key,
                              Supplier<T> supplier,
                              Class<T> clazz) {
        return query(key, null, null, supplier, clazz);
    }


    /**
     * 缓存穿透封装
     * @param key
     * @param expireTime
     * @param timeUnit
     * @param supplier
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T query(String key,
                              Long expireTime, TimeUnit timeUnit,
                              Supplier<T> supplier,
                              Class<T> clazz)
    {
        String resultJsonStr = JEDIS.get(key);
        if (resultJsonStr != null && !resultJsonStr.isEmpty() && !EMPTY_VALUE_STR.equals(resultJsonStr)) {
            return JSON.parseObject(resultJsonStr, clazz);
        }
        if (EMPTY_VALUE_STR.equals(resultJsonStr)) {
            return null;
        }

        T result = supplier.get();
        String value = Objects.nonNull(result) ? JSON.toJSONString(result) : EMPTY_VALUE_STR;
        if (Objects.nonNull(expireTime)) {
            JEDIS.setex(key, timeUnit.toSeconds(expireTime), value);
        }
        else {
            JEDIS.set(key, value);
        }
        return result;
    }

}
